package com.hotel.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotel.common.Result;
import com.hotel.entity.CheckinRecord;
import com.hotel.service.CheckinRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 入住记录管理控制器
 * 
 * @author Hotel Management Team
 */
@RestController
@RequestMapping("/checkin-record")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class CheckinRecordController {

    private final CheckinRecordService checkinRecordService;

    /**
     * 分页查询入住记录
     */
    @GetMapping("/list")
    public Result<Page<CheckinRecord>> getCheckinRecordPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long roomId,
            @RequestParam(required = false) Long memberId) {
        
        // 构建查询条件
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CheckinRecord> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("guest_name", keyword)
                .or().like("guest_phone", keyword)
                .or().like("order_no", keyword));
        }
        
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq("status", status);
        }
        
        if (roomId != null) {
            queryWrapper.eq("room_id", roomId);
        }
        
        if (memberId != null) {
            queryWrapper.eq("member_id", memberId);
        }
        
        queryWrapper.orderByDesc("checkin_time");
        
        Page<CheckinRecord> page = new Page<>(current, size);
        Page<CheckinRecord> result = checkinRecordService.page(page, queryWrapper);
        
        return Result.success(result);
    }

    /**
     * 获取入住记录详情
     */
    @GetMapping("/{id}")
    public Result<CheckinRecord> getCheckinRecordById(@PathVariable Long id) {
        CheckinRecord record = checkinRecordService.getById(id);
        if (record != null) {
            return Result.success(record);
        } else {
            return Result.error("入住记录不存在");
        }
    }

    /**
     * 根据订单号获取入住记录
     */
    @GetMapping("/order/{orderNo}")
    public Result<CheckinRecord> getCheckinRecordByOrderNo(@PathVariable String orderNo) {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CheckinRecord> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        
        CheckinRecord record = checkinRecordService.getOne(queryWrapper);
        if (record != null) {
            return Result.success(record);
        } else {
            return Result.error("入住记录不存在");
        }
    }

    /**
     * 创建入住记录
     */
    @PostMapping
    public Result<Void> createCheckinRecord(@Valid @RequestBody CheckinRecord checkinRecord) {
        boolean success = checkinRecordService.save(checkinRecord);
        if (success) {
            return Result.success("入住记录创建成功");
        } else {
            return Result.error("入住记录创建失败");
        }
    }

    /**
     * 更新入住记录
     */
    @PutMapping("/{id}")
    public Result<Void> updateCheckinRecord(@PathVariable Long id, @Valid @RequestBody CheckinRecord checkinRecord) {
        checkinRecord.setId(id);
        boolean success = checkinRecordService.updateById(checkinRecord);
        if (success) {
            return Result.success("入住记录更新成功");
        } else {
            return Result.error("入住记录更新失败");
        }
    }

    /**
     * 删除入住记录
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteCheckinRecord(@PathVariable Long id) {
        boolean success = checkinRecordService.removeById(id);
        if (success) {
            return Result.success("入住记录删除成功");
        } else {
            return Result.error("入住记录删除失败");
        }
    }

    /**
     * 获取会员入住记录
     */
    @GetMapping("/member/{memberId}")
    public Result<List<CheckinRecord>> getMemberCheckinRecords(@PathVariable Long memberId) {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CheckinRecord> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("member_id", memberId)
                   .orderByDesc("checkin_time");
        
        List<CheckinRecord> records = checkinRecordService.list(queryWrapper);
        return Result.success(records);
    }

    /**
     * 获取房间入住记录
     */
    @GetMapping("/room/{roomId}")
    public Result<List<CheckinRecord>> getRoomCheckinRecords(@PathVariable Long roomId) {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CheckinRecord> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("room_id", roomId)
                   .orderByDesc("checkin_time");
        
        List<CheckinRecord> records = checkinRecordService.list(queryWrapper);
        return Result.success(records);
    }

    /**
     * 获取当前在住客人
     */
    @GetMapping("/current-guests")
    public Result<List<CheckinRecord>> getCurrentGuests() {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CheckinRecord> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("status", "checkedin")
                   .orderByDesc("checkin_time");
        
        List<CheckinRecord> records = checkinRecordService.list(queryWrapper);
        return Result.success(records);
    }

    /**
     * 办理退房
     */
    @PutMapping("/{id}/checkout")
    public Result<Void> checkout(@PathVariable Long id) {
        CheckinRecord record = checkinRecordService.getById(id);
        if (record == null) {
            return Result.error("入住记录不存在");
        }
        
        if (!"checkedin".equals(record.getStatus())) {
            return Result.error("该记录不是入住状态，无法办理退房");
        }
        
        record.setStatus("checkedout");
        record.setCheckoutTime(java.time.LocalDateTime.now());
        
        boolean success = checkinRecordService.updateById(record);
        if (success) {
            return Result.success("退房办理成功");
        } else {
            return Result.error("退房办理失败");
        }
    }
}